package com.example.pointxytest.activity;

import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.example.pointxytest.R;

import java.io.DataInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * FileName: StartActivity
 * Author: huangyuguang
 * Date: 2022/5/9
 * Description: 选择文件
 */
public class StartActivity extends AppCompatActivity implements View.OnClickListener {
    private final int EXTERNAL_STORAGE_CODE = 100;
    private final int CHOOSE_PHOTO1 = 1;
    private final int CHOOSE_PHOTO2 = 2;
    private final int CHOOSE_FILE = 3;
    private ImageView ivDiTu;
    private ImageView ivTuYa;
    private TextView tvFile;
    private EditText etEmail;

    private Uri uriDiTu,uriTuYa,uriFile;
    private ArrayList<float[]> points;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);

        ivDiTu = findViewById(R.id.iv_ditu);
        ivTuYa = findViewById(R.id.iv_tuya);
        tvFile = findViewById(R.id.tv_file);
        etEmail = findViewById(R.id.et_email);
        ivDiTu.setOnClickListener(this);
        ivTuYa.setOnClickListener(this);
        tvFile.setOnClickListener(this);
        findViewById(R.id.tv_go).setOnClickListener(this);
    }

    protected boolean checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> permissions = new ArrayList<>();
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            }
            if (permissions.size() != 0) {
                ActivityCompat.requestPermissions(this, permissions.toArray(new String[0]), EXTERNAL_STORAGE_CODE);
                return false;
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == EXTERNAL_STORAGE_CODE) {
            boolean granted = true;
            for (int result : grantResults) {
                granted = (result == PackageManager.PERMISSION_GRANTED);
                if (!granted) break;
            }
            if (granted) {
                //do something
            } else {
                ToastUtils.showLong("权限不足");
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            switch (requestCode){
                case CHOOSE_PHOTO1:
                    if(data != null){
                        uriDiTu = data.getData();
                        ivDiTu.setImageURI(uriDiTu);
                    }
                    break;
                case CHOOSE_PHOTO2:
                    if(data != null){
                        uriTuYa = data.getData();
                        ivTuYa.setImageURI(uriTuYa);
                    }
                    break;
                case CHOOSE_FILE:
                    if(data.getClipData() != null) {//有选择多个文件
                        int count = data.getClipData().getItemCount();
                        int currentItem = 0;
                        while(currentItem < count) {
                            Uri imageUri = data.getClipData().getItemAt(currentItem).getUri();
                            currentItem = currentItem + 1;
                        }
                    } else if(data.getData() != null) {//只有一个文件咯
                        points = getPointsOnLine(data.getData());
                        if(points != null && points.size() > 0){
                            uriFile = data.getData();
                            tvFile.setText(uriFile.getPath());
                        }else {
                            ToastUtils.showLong("文件内容不正确");
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onClick(View v) {
        if(!checkPermission()) return;
        int id = v.getId();
        switch (id){
            case R.id.iv_ditu:
                openAlbum(CHOOSE_PHOTO1);
                break;
            case R.id.iv_tuya:
                openAlbum(CHOOSE_PHOTO2);
                break;
            case R.id.tv_file:
                openSystemFile();
                break;
            case R.id.tv_go:
                if(checkEmpty()){
                    Intent intent = new Intent(this, Main1Activity.class);
                    intent.putExtra("uriDiTu",uriDiTu);
                    intent.putExtra("uriTuYa",uriTuYa);
                    intent.putExtra("uriFile",uriFile);
                    intent.putExtra("email",etEmail.getText().toString().trim());
                    startActivity(intent);
                }
                break;
        }
    }

    private boolean checkEmpty(){
        if(uriDiTu == null){
            ToastUtils.showLong("请选择底图");
            return false;
        }
        if(uriTuYa == null){
            ToastUtils.showLong("请选择轨迹图");
            return false;
        }
        if(uriFile == null){
            ToastUtils.showLong("请选择坐标文件");
            return false;
        }
        if(!RegexUtils.isEmail(etEmail.getText().toString().trim())){
            ToastUtils.showLong("请输入正确的邮箱地址");
            return false;
        }
        return true;
    }

    private void openAlbum(int requestCode){
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent,requestCode); //打开相册
    }


    public void openSystemFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false);//打开多个文件
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        try {
            startActivityForResult(Intent.createChooser(intent, "请选择文件"), CHOOSE_FILE);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
            ToastUtils.showLong("请安装文件管理器");
        }
    }

    private ArrayList<float[]> getPointsOnLine(Uri uri){

        ArrayList<float[]> points = new ArrayList<>();
        try {
            InputStream fis = getContentResolver().openInputStream(uri);
            DataInputStream dis = new DataInputStream(fis);
            String strLine = null;
            while ((strLine = dis.readLine()) != null){
                if(strLine.length() > 0 || strLine.contains(",")){
                    String str[] = strLine.split(",");
                    float[] floats = new float[]{Float.parseFloat(str[0]),Float.parseFloat(str[1])};
                    points.add(floats);
                }
            }
            dis.close();
            fis.close();
        }catch (Exception e){}
        return points;
    }

}
